package com.baymax.study.tuLing.nio;

import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author baymax
 * @since 2025-06-27
 */
public class NioBlockDemo {
    public static final int PORT = 60001;

    static class Server {
        public static void main(String[] args) throws Exception {
            // 单线程服务器，nio的阻塞模式
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(PORT));

            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
            List<SocketChannel> socketChannels = new ArrayList<>();
            while (true) {
                System.out.println("等待连接...");
                SocketChannel sc = ssc.accept(); // 阻塞
                System.out.println("连接成功");
                socketChannels.add(sc);
                for (SocketChannel channel : socketChannels) {
                    System.out.println("开始读取数据...");
                    channel.read(byteBuffer); // 阻塞
                    byteBuffer.flip();
                    System.out.println(StandardCharsets.UTF_8.decode(byteBuffer));
                    byteBuffer.clear();
                }
            }
        }
    }

    static class Client {
        public static void main(String[] args) throws Exception {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("127.0.0.1", PORT));
            System.out.println("连接成功");
            new Timer().schedule(new TimerTask() {
                @SneakyThrows
                @Override
                public void run() {
                    System.out.println("开始发送数据...");
                    sc.write(ByteBuffer.wrap("hello client".getBytes()));
                    System.out.println("数据发送完毕");
                    sc.close();
                }
            }, 2000);
        }
    }
}
